package com.rayboot.footpoint.provider;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.rayboot.footpoint.model.Category;
import com.rayboot.footpoint.model.Footprint;

public class FootprintManager {
	private static final String[] CATEGORY_PROJECTION;
	private static final String[] FOOTPRINT_PROJECTION;
	private static final String TAG = "FootprintManager";
	private static int idxAccuracy;
	private static int idxAddr;
	private static int idxAudioLength;
	private static int idxAudioName;
	private static int idxAudioPath;
	private static int idxCategory;
	private static int idxComment;
	private static int idxCreateTime;
	private static int idxDrawableId;
	private static int idxId;
	private static int idxLatitude;
	private static int idxLongitude;
	private static int idxName;
	private static int idxPicName;
	private static int idxPicPath;
	private static int idxRate;
	private static int idxShortDate;
	private static int idxSite;
	private static int idxTel;
	private static int idxVersion;
	private static FootprintManager mInstance = null;
	private ContentResolver mDB = null;

	static {
		String[] footprint = new String[20];
		footprint[0] = "_id";
		footprint[1] = "name";
		footprint[2] = "tel";
		footprint[3] = "addr";
		footprint[4] = "comment";
		footprint[5] = "category";
		footprint[6] = "create_time";
		footprint[7] = "latitude";
		footprint[8] = "longitude";
		footprint[9] = "site";
		footprint[10] = "rate";
		footprint[11] = "drawable_id";
		footprint[12] = "version";
		footprint[13] = "audio_path";
		footprint[14] = "pic_path";
		footprint[15] = "accuracy";
		footprint[16] = "pic_name";
		footprint[17] = "audio_name";
		footprint[18] = "audio_length";
		footprint[19] = "short_date";
		FOOTPRINT_PROJECTION = footprint;
		String[] categories = new String[3];
		categories[0] = "keyword";
		categories[1] = "name";
		categories[2] = "icon_id";
		CATEGORY_PROJECTION = categories;
		idxId = -1;
		idxName = -1;
		idxTel = -1;
		idxAddr = -1;
		idxComment = -1;
		idxCategory = -1;
		idxCreateTime = -1;
		idxLatitude = -1;
		idxLongitude = -1;
		idxSite = -1;
		idxRate = -1;
		idxDrawableId = -1;
		idxVersion = -1;
		idxAudioPath = -1;
		idxPicPath = -1;
		idxAccuracy = -1;
		idxPicName = -1;
		idxAudioName = -1;
		idxAudioLength = -1;
		idxShortDate = -1;
	}

	private FootprintManager(Context context) {
		this.mDB = context.getContentResolver();
	}

	public static boolean checkContentValues(ContentValues contentValues) {
		if (TextUtils.isEmpty(contentValues.getAsString("name"))
				|| TextUtils.isEmpty(contentValues.getAsString("pic_path"))
				|| contentValues.getAsLong("create_time").longValue() == 0L) {
			return false;
		}
		return true;
	}

	public static boolean checkContentValues(Footprint footprint) {
		if (TextUtils.isEmpty(footprint.mName)
				|| TextUtils.isEmpty(footprint.mPicPath)
				|| footprint.mCreateTime == 0L) {
			return false;
		}
		return true;
	}

	private void fillDataFromCursor(Category category, Cursor cursor) {
		category.mKeyword = cursor.getString(cursor
				.getColumnIndexOrThrow("keyword"));
		category.mName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
		category.mIconID = cursor.getInt(cursor
				.getColumnIndexOrThrow("icon_id"));
	}

	public static void fillDataFromCursor(Footprint paramFootprint,
			Cursor paramCursor) {
		if (idxId == -1) {
			idxId = paramCursor.getColumnIndexOrThrow("_id");
			idxName = paramCursor.getColumnIndexOrThrow("name");
			idxTel = paramCursor.getColumnIndexOrThrow("tel");
			idxAddr = paramCursor.getColumnIndexOrThrow("addr");
			idxComment = paramCursor.getColumnIndexOrThrow("comment");
			idxCategory = paramCursor.getColumnIndexOrThrow("category");
			idxCreateTime = paramCursor.getColumnIndexOrThrow("create_time");
			idxLatitude = paramCursor.getColumnIndexOrThrow("latitude");
			idxLongitude = paramCursor.getColumnIndexOrThrow("longitude");
			idxSite = paramCursor.getColumnIndexOrThrow("site");
			idxRate = paramCursor.getColumnIndexOrThrow("rate");
			idxDrawableId = paramCursor.getColumnIndexOrThrow("drawable_id");
			idxVersion = paramCursor.getColumnIndexOrThrow("version");
			idxAudioPath = paramCursor.getColumnIndexOrThrow("audio_path");
			idxPicPath = paramCursor.getColumnIndexOrThrow("pic_path");
			idxAccuracy = paramCursor.getColumnIndexOrThrow("accuracy");
			idxPicName = paramCursor.getColumnIndexOrThrow("pic_name");
			idxAudioName = paramCursor.getColumnIndexOrThrow("audio_name");
			idxAudioLength = paramCursor.getColumnIndexOrThrow("audio_length");
			idxShortDate = paramCursor.getColumnIndexOrThrow("short_date");
		}
		paramFootprint.setID(paramCursor.getInt(idxId));
		paramFootprint.mName = paramCursor.getString(idxName);
		paramFootprint.mTel = paramCursor.getString(idxTel);
		paramFootprint.mAddr = paramCursor.getString(idxAddr);
		paramFootprint.mComment = paramCursor.getString(idxComment);
		paramFootprint.mCategory = paramCursor.getString(idxCategory);
		paramFootprint.mCreateTime = paramCursor.getLong(idxCreateTime);
		paramFootprint.mLatitude = paramCursor.getInt(idxLatitude);
		paramFootprint.mLongitude = paramCursor.getInt(idxLongitude);
		paramFootprint.mSite = paramCursor.getString(idxSite);
		paramFootprint.mRate = paramCursor.getInt(idxRate);
		paramFootprint.mDrewableID = paramCursor.getLong(idxDrawableId);
		paramFootprint.mVersion = paramCursor.getInt(idxVersion);
		paramFootprint.mAudioPath = paramCursor.getString(idxAudioPath);
		paramFootprint.mPicPath = paramCursor.getString(idxPicPath);
		paramFootprint.mAccuracy = paramCursor.getInt(idxAccuracy);
		paramFootprint.mPicFileName = paramCursor.getString(idxPicName);
		paramFootprint.mAudioFileName = paramCursor.getString(idxAudioName);
		paramFootprint.mVoiceSampleLength = paramCursor
				.getFloat(idxAudioLength);
		paramFootprint.mShortDate = paramCursor.getString(idxShortDate);
	}

	private void fillVauleFromCategory(ContentValues ocntentValues,
			Category category) {
		ocntentValues.put("keyword", category.mKeyword);
		ocntentValues.put("name", category.mName);
		ocntentValues.put("icon_id", Integer.valueOf(category.mIconID));
	}

	public static void fillVauleFromFootprint(ContentValues contentValues,
			Footprint footprint) {
		if (footprint.getID() == -1) {
			contentValues.put("_id", Integer.valueOf(footprint.getID()));
			SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(
					"MM/dd/yy");
			contentValues.put("name", footprint.mName);
			contentValues.put("tel", footprint.mTel);
			contentValues.put("addr", footprint.mAddr);
			contentValues.put("comment", footprint.mComment);
			contentValues.put("category", footprint.mCategory);
			contentValues.put("create_time",
					Long.valueOf(footprint.mCreateTime));
			contentValues.put("latitude", Integer.valueOf(footprint.mLatitude));
			contentValues.put("longitude",
					Integer.valueOf(footprint.mLongitude));
			contentValues.put("site", footprint.mSite);
			contentValues.put("rate", Integer.valueOf(footprint.mRate));
			contentValues.put("drawable_id",
					Long.valueOf(footprint.mDrewableID));
			contentValues.put("version", Integer.valueOf(footprint.mVersion));
			contentValues.put("audio_path", footprint.mAudioPath);
			contentValues.put("pic_path", footprint.mPicPath);
			contentValues.put("accuracy", Integer.valueOf(footprint.mAccuracy));
			contentValues.put("pic_name", footprint.mPicFileName);
			contentValues.put("audio_name", footprint.mAudioFileName);
			contentValues.put("audio_length",
					Float.valueOf(footprint.mVoiceSampleLength));
			contentValues.put("short_date", localSimpleDateFormat
					.format(new Date(footprint.mCreateTime)));
		}
	}

	public static FootprintManager getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new FootprintManager(context.getApplicationContext());
		}
		return mInstance;
	}

	private String quotedStr(String paramString) {
		return "'" + paramString + "'";
	}

	public Uri addCategory(Category paramCategory) {
		ContentValues localContentValues = new ContentValues();
		fillVauleFromCategory(localContentValues, paramCategory);
		return this.mDB.insert(CategoryProvider.CategoryColumns.CONTENT_URI,
				localContentValues);
	}

	public void addCategory(Category[] paramArrayOfCategory) {
		for (Category category : paramArrayOfCategory) {
			addCategory(category);
		}
	}

	public int addFootprint(Footprint footprint) {
		try {
			ContentValues contentValues = new ContentValues();
			fillVauleFromFootprint(contentValues, footprint);
			Uri uri = null;
			if (checkContentValues(contentValues)) {
				uri = this.mDB.insert(
						FootprintsProvider.FootprintColumns.CONTENT_URI,
						contentValues);
			}
			if (uri != null) {
				return Integer.parseInt(uri.getLastPathSegment());
			}
			return -1;
		} finally {
		}
	}

	public void addFootprint(Footprint[] paramArrayOfFootprint) {
		for (Footprint footprint : paramArrayOfFootprint) {
			addFootprint(footprint);
		}
	}

	public void addNonDuplicatedFootprint(Footprint[] paramArrayOfFootprint) {
		int i = paramArrayOfFootprint.length;
		for (int j = 0; j < i; j++) {
			Footprint localFootprint = paramArrayOfFootprint[j];
			if ((!checkContentValues(localFootprint))
					|| (checkExistedFootprintByCreateTime(localFootprint.mCreateTime)))
				continue;
			addFootprint(localFootprint);
		}
	}

	public boolean checkExistedFootprintByCreateTime(long paramLong) {
		int i = 0;
		String str = "create_time = '" + paramLong + "'";
		Cursor cursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, null);

		if (cursor.getCount() <= 0) {
			cursor.close();
			return false;
		} else {
			cursor.close();
			return true;
		}
	}

	public Category findCategory(String paramString) {
		String str = "keyword = '" + paramString + "'";
		Cursor cursor = this.mDB.query(
				CategoryProvider.CategoryColumns.CONTENT_URI,
				CATEGORY_PROJECTION, str, null, null);
		Category category = null;
		if (cursor.moveToNext()) {
			category = new Category();
			fillDataFromCursor(category, cursor);
		}
		cursor.close();
		return category;
	}

	public ArrayList<Footprint> findFootprintByCategory(String paramString1,
			String paramString2) {
		ArrayList localArrayList = new ArrayList();
		String str = null;
		if ((paramString1 != null) && (!paramString1.equals(""))
				&& (!paramString1.equals(Category.getAllCategory().mKeyword)))
			str = "category  = " + quotedStr(paramString1);
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, paramString2);
		while (localCursor.moveToNext()) {
			Footprint localFootprint = new Footprint();
			fillDataFromCursor(localFootprint, localCursor);
			localArrayList.add(localFootprint);
		}
		localCursor.close();
		return localArrayList;
	}

	public ArrayList<Footprint> findFootprintByMatchString(String paramString1,
			String paramString2, String paramString3) {
		new Footprint();
		String str = "name like '%" + paramString2 + "%'";
		if ((paramString1 != null) && (!paramString1.equals("")))
			str = str + " AND category  = " + quotedStr(paramString1);
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, paramString3);
		localCursor.deactivate();
		ArrayList localArrayList = new ArrayList(localCursor.getCount());
		while (localCursor.moveToNext()) {
			Footprint localFootprint = new Footprint();
			fillDataFromCursor(localFootprint, localCursor);
			localArrayList.add(localFootprint);
		}
		localCursor.close();
		return localArrayList;
	}

	public Cursor findFootprintCursorByCategory(String paramString1,
			String paramString2) {
		String str = null;
		if ((paramString1 != null) && (!paramString1.equals(""))
				&& (!paramString1.equals(Category.getAllCategory().mKeyword)))
			str = "category  = " + quotedStr(paramString1);
		return this.mDB.query(FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, paramString2);
	}

	public Cursor findFootprintCursorByCategoryAndKeyword(String paramString1,
			String paramString2) {
		String str = "accuracy > 0 ";
		if ((paramString1 != null) && (!paramString1.equals(""))
				&& (!paramString1.equals(Category.getAllCategory().mKeyword)))
			str = str + "AND category  = " + quotedStr(paramString1);
		if ((paramString2 != null) && (!paramString2.equals("")))
			str = str
					+ "AND name  like "
					+ quotedStr(new StringBuilder().append("%")
							.append(paramString2).toString());
		return this.mDB.query(FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, null);
	}

	public ArrayList<Footprint> findFootprintWithoutMatchString(
			String paramString1, String paramString2, String paramString3) {
		new Footprint();
		String str = "name not in (select name from footprint where name like '%"
				+ paramString2 + "%')";
		if ((paramString1 != null) && (!paramString1.equals("")))
			str = str + " AND category  = " + quotedStr(paramString1);
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, paramString3);
		ArrayList localArrayList = new ArrayList(localCursor.getCount());
		localCursor.moveToFirst();
		while (localCursor.moveToNext()) {
			Footprint localFootprint = new Footprint();
			fillDataFromCursor(localFootprint, localCursor);
			localArrayList.add(localFootprint);
		}
		localCursor.close();
		return localArrayList;
	}

	public ArrayList<Category> getAllCategory() {
		Cursor localCursor = this.mDB.query(
				CategoryProvider.CategoryColumns.CONTENT_URI,
				CATEGORY_PROJECTION, null, null, null);
		localCursor.deactivate();
		ArrayList localArrayList = new ArrayList(localCursor.getCount());
		while (localCursor.moveToNext()) {
			Category localCategory = new Category();
			fillDataFromCursor(localCategory, localCursor);
			localArrayList.add(localCategory);
		}
		localCursor.close();
		return localArrayList;
	}

	public Cursor getCursorSortBy(String paramString1, String paramString2,
			String paramString3) {
		StringBuilder localStringBuilder = new StringBuilder();
		if ((paramString1 != null) && (!paramString1.equals("")))
			localStringBuilder.append("category").append(" = ")
					.append(quotedStr(paramString1));
		if ((paramString2 != null) && (!paramString2.equals(""))) {
			if (localStringBuilder.length() <= 0) {
				return null;
			} else {
				localStringBuilder.append(" AND (");
			}
		}
		while (true) {
			localStringBuilder.append("name").append(" like '% ")
					.append(paramString2).append("%' ");
			localStringBuilder.append(" OR ");
			localStringBuilder.append("name").append(" like '")
					.append(paramString2).append("%' ");
			localStringBuilder.append(" OR ");
			localStringBuilder.append("addr").append(" like '% ")
					.append(paramString2).append("%' ");
			localStringBuilder.append(" OR ");
			localStringBuilder.append("addr").append(" like '")
					.append(paramString2).append("%') ");
			return this.mDB.query(
					FootprintsProvider.FootprintColumns.CONTENT_URI,
					FOOTPRINT_PROJECTION, localStringBuilder.toString(), null,
					paramString3);
		}
	}

	public long getExistFootprintID(Footprint paramFootprint) {
		long l = -1L;
		String str = null;
		if (paramFootprint.mCreateTime > 0L)
			str = "create_time = '" + paramFootprint.mCreateTime + "'";
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, null);
		if (localCursor.moveToNext())
			l = localCursor.getLong(localCursor.getColumnIndexOrThrow("_id"));
		localCursor.close();
		return l;
	}

	public ArrayList<Footprint> getFootprintAll(String paramString) {
		return findFootprintByCategory(null, paramString);
	}

	public Footprint getFootprintById(int paramInt) {
		Footprint localFootprint = new Footprint();
		String str = "_id = '" + String.valueOf(paramInt) + "'";
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, null);
		while (localCursor.moveToNext())
			fillDataFromCursor(localFootprint, localCursor);
		localCursor.close();
		return localFootprint;
	}

	public Footprint getFootprintByName(String paramString) {
		Footprint localFootprint = new Footprint();
		String str = "name = '" + paramString + "'";
		Cursor localCursor = this.mDB.query(
				FootprintsProvider.FootprintColumns.CONTENT_URI,
				FOOTPRINT_PROJECTION, str, null, "create_time desc");
		if (localCursor.moveToNext())
			fillDataFromCursor(localFootprint, localCursor);
		localCursor.close();
		return localFootprint;
	}

	public void modifyCategory(Category paramCategory) {
		ContentValues localContentValues = new ContentValues();
		fillVauleFromCategory(localContentValues, paramCategory);
		String str = "keyword = '" + paramCategory.mKeyword + "'";
		this.mDB.update(CategoryProvider.CategoryColumns.CONTENT_URI,
				localContentValues, str, null);
	}

	public void modifyFootprint(Footprint paramFootprint) {
		ContentValues localContentValues = new ContentValues();
		fillVauleFromFootprint(localContentValues, paramFootprint);
		String str = "_id = '" + String.valueOf(paramFootprint.getID()) + "'";
		this.mDB.update(FootprintsProvider.FootprintColumns.CONTENT_URI,
				localContentValues, str, null);
	}

	public void modifyFootprintbyImport(Footprint paramFootprint) {
		ContentValues localContentValues = new ContentValues();
		fillVauleFromFootprint(localContentValues, paramFootprint);
		String str = "create_time = '" + paramFootprint.mCreateTime + "'";
		this.mDB.update(FootprintsProvider.FootprintColumns.CONTENT_URI,
				localContentValues, str, null);
	}

	public void removeAllFootprint() {
		this.mDB.delete(FootprintsProvider.FootprintColumns.CONTENT_URI, null,
				null);
	}

	public void removeCategory(Category paramCategory) {
		String str = "keyword = '" + paramCategory.mKeyword + "'";
		this.mDB.delete(CategoryProvider.CategoryColumns.CONTENT_URI, str, null);
	}

	public void removeFootprint(int paramInt) {
		removeFootprint(String.valueOf(paramInt));
	}

	public void removeFootprint(Footprint paramFootprint) {
		removeFootprint(paramFootprint.getID());
	}

	public void removeFootprint(String paramString) {
		String str = "_id = '" + paramString + "'";
		this.mDB.delete(FootprintsProvider.FootprintColumns.CONTENT_URI, str,
				null);
	}

	public void removeFootprint(Footprint[] paramArrayOfFootprint) {
		StringBuilder localStringBuilder = new StringBuilder("_id");
		localStringBuilder.append(" in (");
		int i = 1;
		int j = paramArrayOfFootprint.length;
		for (int k = 0; k < j; k++) {
			Footprint localFootprint = paramArrayOfFootprint[k];
			if (i == 0)
				localStringBuilder.append(",");
			i = 0;
			localStringBuilder.append(localFootprint.getID());
		}
		localStringBuilder.append(")");
		this.mDB.delete(FootprintsProvider.FootprintColumns.CONTENT_URI,
				localStringBuilder.toString(), null);
	}
}
